<?php

namespace app\wechat\controller;

use EasyWeChat\Factory;
use EasyWeChat\OpenPlatform\Server\Guard;
use think\Controller;
use think\Db;
use think\facade\Log;
use think\facade\Request;
use DOMDocument;

class Index extends Controller
{

    public $openPlatform;

    public function __construct()
    {
        // 实例第三方平台
        $this->openPlatform = Factory::openPlatform(config('wechat.open_platform.default'));
    }

    public function index()
    {
        $server = $this->openPlatform->server;
        $this->getTricket();
        // 处理授权取消事件
        $server->push(function ($message) {
            $appid = $message['AuthorizerAppid'];
            $res = Db::table('nx_authorizer')->where('appid', $appid)->update(['delstatus' => 4]);
        }, Guard::EVENT_UNAUTHORIZED);
        return $server->serve();
    }
    //获取第三方平台的component_verify_ticket
    public function getTricket()
    {
        $timeStamp = empty($_GET['timestamp']) ? "" : trim($_GET['timestamp']);
        $nonce = empty($_GET['nonce']) ? "" : trim($_GET['nonce']);
        $msg_sign = empty($_GET['msg_signature']) ? "" : trim($_GET['msg_signature']);
        $encryptMsg = file_get_contents('php://input');
        $pc = new wxBizMsg();
        $xml_tree = new DOMDocument();
        $xml_tree->loadXML($encryptMsg);
        $array_e = $xml_tree->getElementsByTagName('Encrypt');
        $encrypt = $array_e->item(0)->nodeValue;
        $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
        $from_xml = sprintf($format, $encrypt);
        $msg = '';
        $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
        if ($errCode == 0) {
            $xml = new DOMDocument();
            $xml->loadXML($msg);
            $array_e = $xml->getElementsByTagName('ComponentVerifyTicket');
            $component_verify_ticket = $array_e->item(0)->nodeValue;
            DB::name('nx_system')->where(['delstatus' => 1, 'title' => 'wechat_verifyticket'])->update(['title' => 'wechat_verifyticket', 'content' => $component_verify_ticket, 'updatetime' => date('Y-m-d H:i:s', time())]);
            echo 'success';
        } else {
            DB::name('nx_system')->where(['delstatus' => 1, 'title' => 'errorcode'])->update(['title' => 'errorcode', 'content' => $errCode, 'updatetime' => date('Y-m-d H:i:s', time())]);
            Log::record($errCode);
        }
    }

    public function callback(Request $request)
    {
        $info = $this->openPlatform->handleAuthorize();
        $appid = $info['authorization_info']['authorizer_appid'];
        $refresh_token = $info['authorization_info']['authorizer_refresh_token'];
        $auth = $this->openPlatform->getAuthorizer($appid);
        $nick_name = $auth['authorizer_info']['nick_name'];
        $gh_id = $auth['authorizer_info']['user_name'];
        $head_img = $auth['authorizer_info']['head_img'];
        $company = $auth['authorizer_info']['principal_name'];
        $verify_type_info = $auth['authorizer_info']['verify_type_info']['id'];
        $createtime = date('Y-m-d H:i:s', time());
        $data = ['name' => $nick_name, 'ghid' => $gh_id, 'appid' => $appid, 'pic' => $head_img, 'is_verify' => $verify_type_info, 'company' => $company, 'refresh_token' => $refresh_token, 'createtime' => $createtime];
        $res = Db::name('nx_authorizer')->insert($data, true);
        if ($res) {
            return '授权成功';
        } else {
            return '授权失败';
        }
    }

    // 获取授权链接
    public function get_preauth_url()
    {
        $url = $this->openPlatform->getPreAuthorizationUrl('http://wechat.nanxuncn.cn/wechat/index/callback');
        return $url;
    }

    // 获取所有授权方
    public function get_authorizers($offset = 0, $count = 500)
    {
        $authorizers = $this->openPlatform->getAuthorizers($offset, $count);
        $list = $authorizers['list'];
        $res = array();

        foreach ($list as $item) {
            $a = $this->openPlatform->getAuthorizer($item['authorizer_appid']);
            $b['nick_name'] = $a['authorizer_info']['nick_name'];
            $b['gh_id'] = $a['authorizer_info']['user_name'];
            $b['appid'] = $item['authorizer_appid'];
            array_push($res, $b);
        }

        return json($res);
    }
}
